import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  $empty,
  $toast,
  storage,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {

    id: 0,
    content: '',
    fileList: [],
    fileList_xq: [],
    videoList: [],
    biaoti: "商品标题",
    jiage: "商品价格",
    miaoshu: "商品描述",
    biaoti_tips: "请填写商品标题",
    jiage_tips: "请填写商品价格",
    zhekoujia_tips: "请填写商品超低底价",
    miaoshu_tips: "请填写商品描述",
    shoptype: 0,
    userShow: false,
    addressForm: {
      title: '',
      description: '',
      Category: '',
      username: '',
      price: '',
      discount_price: '',
      mobile: '',
      orders: '',
      brand: '',
      isdesign: false
    },
    isPrice: true,
    sekaShow: false,
    sekaArr: [],
    sekaList: [],
    seka_ids: [],
    rule: '#title,#description,#price,#discount_price,#categoryid'
  },
  ondesignChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      "addressForm.isdesign": detail
    });
  },
  onPriceChange({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    let rule = '#title,#description,#price,#discount_price,#categoryid'
    if (!detail) rule = '#title,#description,#categoryid'
    this.setData({
      isPrice: detail,
      rule
    });
    Validate.rules(rule, (res) => {
      this.expressValidate = res;
    });
  },
  toggle(type) {
    this.setData({
      [type]: !this.data[type]
    });
  },
  pickerCategoryTap() {
    this.toggle('categoryShow');
    let {
      columns,
      addressForm
    } = this.data;
    let cateId = columns.indexOf(addressForm.Category)
    this.setData({
      cate_index: cateId
    });
  },
  ordersInput(e) {
    this.setData({
      ordersError: '',
      "addressForm.orders": $empty(e.detail)
    })
  },
  brandInput(e) {
    this.setData({
      brandError: '',
      "addressForm.brand": $empty(e.detail)
    })
  },
  pickerUserTap() {
    this.toggle('userShow');
  },
  titleInput(e) {
    this.setData({
      titleInputError: '',
      'addressForm.title': e.detail,
    });
  },
  mobileInput(e) {
    this.setData({
      ordersInputError: '',
      'addressForm.mobile': e.detail,
    });
  },
  descriptionInput(e) {
    this.setData({
      descriptionInputError: '',
      'addressForm.description': e.detail,
    });
  },
  priceInput(e) {
    this.setData({
      priceInputError: '',
      'addressForm.price': e.detail,
    });
  },
  discountPriceInput(e) {
    this.setData({
      priceInputError: '',
      'addressForm.discount_price': e.detail,
    });
  },
  goanli() {
    wxApi.navigateTo(getPage.guanlian, {
      id: this.data.id
    });
  },
  /**
   * 删除商品事件
   */
  handleDelProduct() {
    const that = this;
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '是否删除？',
      success(res) {
        if (res.confirm) {
          const shopInfo = that.data.shopInfo;
          http.post(api.default, {
            data: {
              action: 'del_product',
              shopid: that.data.shopid,
              id: that.data.id,
            }
          }).then((res) => {
            $toast(`删除成功`, {
              icon: 'success'
            });
            const pages = getCurrentPages()[getCurrentPages().length - 2];

            wx.navigateBack({
              delta: 1,
              success() {
                if (pages !== undefined || pages !== null) {
                  pages.data.pageChange = 1;
                  if (pages.delOnload) pages.delOnload();
                  pages.onLoad();
                }
              }
            });
          })
        }
      },
    })
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      'addressForm.Category': value,
      categoryInputError: ''
    })
    this.toggle('categoryShow');
  },
  onUserChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      'addressForm.username': value,
      usernameInputError: ''
    })
    this.toggle('userShow');
  },
  deleteimg(event) {
    var index = event.detail.index;
    var fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    });
  },
  deleteimgxq(event) {
    var index = event.detail.index;
    var fileList_xq = this.data.fileList_xq;
    fileList_xq.splice(index, 1);
    this.setData({
      fileList_xq: fileList_xq
    });
  },
  deletevideo(event) {
    var index = event.detail.index;
    var videoList = this.data.videoList;
    videoList.splice(index, 1);
    this.setData({
      videoList: videoList
    });
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList = that.data.fileList;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "products",
        success(res) {
          // 上传完成需要更新 fileList

          fileList.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList: fileList
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  afterReadxq(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList_xq = that.data.fileList_xq;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "products",
        success(res) {

          fileList_xq.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList_xq: fileList_xq
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  // 打开色卡弹窗
  addSeka() {
    this.setData({
      sekaShow: true
    })
    const {
      shopid,
      seka_ids
    } = this.data;
    let ids = seka_ids.length > 0 ? seka_ids.join() : ''
    http.post(api.default, {
      data: {
        action: 'selectseka',
        shopid,
        ids
      }
    }).then(res => {
      let sekaList = res.data.data;
      this.setData({
        sekaList
      })
    })
  },
  selectSeka(e) {
    console.log('eeee', e)
    let sekaList = this.data.sekaList;
    let selId = e.currentTarget.dataset.id;
    sekaList.forEach(item => {
      if (item.id == selId) {
        item.ischek = !item.ischek
      }
    })
    this.setData({
      sekaList
    })
  },
  // 删除色卡
  delSeka(e) {
    let id = e.currentTarget.dataset.id;
    console.log('ee', id)
    let sekaArrCopy = this.data.sekaArr;
    let seka_ids_c = this.data.seka_ids;
    sekaArrCopy = sekaArrCopy.filter(f => f.id != id)
    seka_ids_c = seka_ids_c.filter(f => f != id)
    this.setData({
      sekaArr: sekaArrCopy,
      seka_ids: seka_ids_c
    })
  },
  onsekaClose() {
    this.setData({
      sekaShow: false
    })
  },
  // 确认添加色卡
  confirmSeka() {
    let sekaList = this.data.sekaList;
    let sekaArr = this.data.sekaArr;
    let sekaArrFil = sekaList.filter(f => f.ischek);
    let sekaArrRes = sekaArr.concat(sekaArrFil)
    let seka_ids = sekaArrRes.map(m => m.id)
    this.setData({
      sekaArr: sekaArrRes,
      seka_ids
    })
    this.onsekaClose()
  },
  /**
   * 提交保存
   */
  anliForm(e) {
    Validate.check(this, this.expressValidate, e.detail.value, (res) => {
      console.log('rew', res)
      if (res) {
        const data = this.data;
        const fileList = data.fileList;
        const fileList_xq = data.fileList_xq;
        if (fileList.length == 0) {
          $toast("请上传图片");
          return;
        }
        const {
          shopid,
          userId,
          id,
          videoList,
          sekaArr,
          isPrice,
          shoptype
        } = this.data;
        const {
          title,
          description,
          price,
          discount_price,
          Category,
          mobile,
          username,
          orders,
          brand,
          isdesign
        } = data.addressForm;
        // if (price == '') {
        //   $toast("请输入商品价格");
        //   return;
        // }
        let postSeka = sekaArr.map(m => {
          return {
            id: m.id,
            title: m.title,
            picurl: m.picurl,
          }
        })
        let jsonSeka = JSON.stringify(postSeka)
        const params = {
          action: 'addproduct',
          id: id,
          title: title,
          description: description,
          isprice: isPrice ? 1 : 0,
          price: !isPrice && shoptype == 2 ? 0 : price,
          discount_price: !isPrice && shoptype == 2 ? 0 : discount_price,
          mobile: mobile,
          username: username == '请选择' ? '' : username,
          userid: userId,
          shopid: shopid,
          shopcategory: Category,
          orders: orders || 0,
          brand: brand,
          fileList: JSON.stringify(fileList),
          xqlist: JSON.stringify(fileList_xq),
          videoList: JSON.stringify(videoList),
          seka: jsonSeka,
          isdesign: isdesign ? 1 : ''
        }
        http.post(api.default, {
          data: params
        }).then((res) => {
          if (res.data.code == 0) {
            $toast('保存成功', {
              icon: 'success'
            });
            const pages = getCurrentPages()[getCurrentPages().length - 2];

            wx.navigateBack({
              delta: 1,
              success() {
                if (pages !== undefined || pages !== null) {
                  pages.data.pageChange = 1;
                  if (pages.onCateProduct) pages.onCateProduct(Category);
                  pages.onLoad();
                }
              }
            });
          } else {
            $toast(res.data.errmsg, {
              icon: 'fail'
            });
          }
        });
      } else {
        // $toast("请输入商品标题、价格和内容");
        this.setData({
          titleInputError: this.data.addressForm.title == "" ? this.data.biaoti_tips : '',
          priceInputError: this.data.addressForm.price == "" ? this.data.jiage_tips : '',
          discountPriceInputError: this.data.addressForm.discount_price == "" ? this.data.zhekoujia_tips : '',
          categoryInputError: this.data.addressForm.Category == "" ? '请选择分类' : '',
          descriptionInputError: this.data.addressForm.description ? '' : this.data.miaoshu_tips

        });
      }
    });

  },

  videoafterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    console.log(file)

    var videoList = that.data.videoList;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "anli",
        success(res) {
          // 上传完成需要更新 fileList
          console.log(res);
          videoList.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            videoList: videoList
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }

    console.log(videoList);
  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    app.getLogin().then(async (res) => {
      console.log('=================', res);
      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop.ShopId,
        shoptype: res.data.shop.ShopType
      });
      if (res.data.shop.ShopType != 2) {
        wx.setNavigationBarTitle({
          title: '添加成员',
        });
        this.setData({
          biaoti: "名称",
          jiage: "职位",
          miaoshu: "详细描述",
          biaoti_tips: "请填写名称",
          jiage_tips: "请填写职位",
          miaoshu_tips: "请填写详细描述"
        })
      }
      if (res.data.shop.ShopType == 3) {
        const res = await http.post(api.default, {
          data: {
            action: 'getallusers',
            shopid: this.data.shopid
          }
        }, false)
        const {
          data
        } = res.data;
        console.log(res.data);
        var users = ['请选择'];
        var userIds = [];
        data.forEach((item, index) => {
          users.push(item.username);
          userIds.push(item.userid);
        });
        this.setData({
          users: users,
          userIds: userIds
        });
      }
      http.post(api.default, {
        data: {
          action: 'getshopcategory',
          shopid: this.data.shopid
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log(res.data);
        var columns = [];
        data.forEach((item, index) => {
          columns.push(item.Title);
        });
        this.setData({
          columns: columns
        });
      });
      if (JSON.stringify(options) !== '{}') {
        if (options.cateStr) {
          this.setData({
            'addressForm.Category': options.cateStr,
          })
        } else if (options.id) {
          this.setData({
            id: options.id
          });
          http.post(api.default, {
            data: {
              action: 'getproductinfo',
              id: options.id
            }
          }).then((res) => {
            const data = res.data.data;
            console.log('data.info.shopcategory', data.info.shopcategory)
            let sekaArr = data.info.seka ? JSON.parse(data.info.seka) : [];
            let seka_ids = sekaArr.map(m => m.id);
            console.log('userIds====', this.data.userIds)
            let u_name = this.data.userIds?.includes(data.info.userid) ? data.info.username : ''
            this.setData({
              'addressForm.title': data.info.productname,
              'addressForm.description': data.info.description,
              'addressForm.price': data.info.marketprice,
              'addressForm.discount_price': data.info.discount_price,
              'addressForm.mobile': data.info.mobile,
              'addressForm.Category': data.info.shopcategory,
              'addressForm.username': u_name,
              'addressForm.orders': data.info.orders,
              'addressForm.brand': data.info.brand,
              'addressForm.isdesign': data?.isdesign ? true : false,
              isPrice: data.info.isprice,
              fileList: data.filelist,
              fileList_xq: data.xqlist,
              videoList: data.videolist,
              sekaArr,
              seka_ids
            });
            if (!this.data.isPrice) {
              this.setData({
                rule: '#title,#description,#categoryid'
              });
              //获取验证规则
              Validate.rules(this.data.rule, (res) => {
                this.expressValidate = res;
              });
            }
          });
        }
      }
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    });


    //获取验证规则
    Validate.rules(this.data.rule, (res) => {
      this.expressValidate = res;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})